package com.blog.security.filter;

import com.alibaba.fastjson2.JSON;
import com.blog.common.CommonRespDto;
import com.blog.common.Constant;
import com.blog.enums.ResponseCodeEnums;
import com.blog.security.config.JwtProperties;
import com.blog.security.util.JwtSecurityUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName TokenFilter
 * @Destription
 * @Author 天堂小野花
 * @Date 2025/8/10  22:24
 * @Version 1.0
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    private final JwtProperties jwtProperties;

    public TokenFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String token = serverHttpRequest.getHeaders().getFirst(Constant.TOKEN);
        //白名单以外的请求，需要携带token
        if(StringUtils.hasLength(token)){
            /*serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
            return getUnAuthorizedMono(serverHttpResponse);*/
            Map<String, Object> stringObjectMap = JwtSecurityUtil.verifyJavaWebToken(token, jwtProperties.getSecretKey());
            if (stringObjectMap == null|| !stringObjectMap.containsKey(Constant.TOKEN_USER_INFO)){
                return getUnAuthorizedMono(serverHttpResponse);
            }
            LinkedHashMap<String, Object> userDetails = (LinkedHashMap) stringObjectMap.get(Constant.TOKEN_USER_INFO);
            ServerHttpRequest mutableReq = serverHttpRequest.mutate().header(Constant.HEADER_USER, (String) userDetails.get(Constant.TOKEN_USER_INFO_USERNAME)).build();
            ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
            return chain.filter(mutableExchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> getUnAuthorizedMono(ServerHttpResponse serverHttpResponse) {
        serverHttpResponse.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        CommonRespDto<Object> responseResult = CommonRespDto.failSec(ResponseCodeEnums.UNAUTHORIZED.getMessage());
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(responseResult).getBytes());
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
